using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Text;
using System.Collections.Specialized;

using SqlWebAdmin.CSharp;

public partial class Export : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
           
                lblError.Text = string.Empty;
                lblError.Visible = false;

				Server smoServer = SmoHelper.GetServer();
                try
                {
                    smoServer.SetDefaultInitFields(typeof(Database), "Name");
                    DatabaseCollection smoDatabases = smoServer.Databases;

                    ddlDatabases.Items.Clear();
                    for (int i = 0; i < smoDatabases.Count; i++)
                    {
                        ddlDatabases.Items.Add(new ListItem(smoDatabases[i].Name));
                    }
                }
                catch (SmoException smoEx)
                {
                    lblError.Text = HttpUtility.HtmlEncode(Common.ConcatenateExceptions(smoEx));
                    lblError.Visible = true;
                }
                catch (System.Exception ex)
                {
                    lblError.Text = HttpUtility.HtmlEncode(Common.ConcatenateExceptions(ex));
                    lblError.Visible = true;
                }

            
        }
    }

    protected void cmdExport_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            
                lblError.Text = string.Empty;
                lblError.Visible = false;

                try
                {
					Server smoServer = SmoHelper.GetServer();

                    string databaseName = ddlDatabases.SelectedItem.Text;
                    bool scriptDatabase = chkScriptDatabase.Checked;
                    bool scriptDrop = chkScriptDrop.Checked;
                    bool scriptTableSchema = chkScriptTableSchema.Checked;
                  
                    bool scriptStoredProcedures = chkScriptStoredProcedures.Checked;
                    bool scriptComments = chkScriptComments.Checked;

                    StringBuilder scriptResult = new StringBuilder();
                    Database smoDatabase;

                    if (!smoServer.Databases.Contains(databaseName))
                    {
                        Response.Redirect(String.Format("error.aspx?error={0}", Globals.databaseNotFoundErrorNumber), false);
                    }
                    else
                    {
                        smoDatabase = smoServer.Databases[databaseName];

                        if (scriptDatabase)
                        {

                            scriptResult.Append("-- DROP script for the Database");
                            scriptResult.Append(Environment.NewLine);
                            scriptResult.Append(Environment.NewLine);

                            ScriptingOptions scriptingOptions = new ScriptingOptions();
                            scriptingOptions.ScriptDrops = scriptDrop;
                            scriptingOptions.IncludeHeaders = scriptComments;

                            StringCollection scripts = smoDatabase.Script(scriptingOptions);
                            foreach (string s in scripts)
                            {
                                scriptResult.Append(s);
                                scriptResult.Append(Environment.NewLine);
                            }


                            scriptResult.Append("-- CREATE script for the Database");
                            scriptResult.Append(Environment.NewLine);
                            scriptResult.Append(Environment.NewLine);

                            scriptingOptions = new ScriptingOptions();
                            scriptingOptions.IncludeHeaders = scriptComments;

                            scripts = smoDatabase.Script(scriptingOptions);
                            foreach (string s in scripts)
                            {
                                scriptResult.Append(s);
                                scriptResult.Append(Environment.NewLine);
                            }


                            scriptResult.Append("-- CREATE script for each item in the Database");
                            scriptResult.Append(Environment.NewLine);
                            scriptResult.Append(Environment.NewLine);

                            Transfer smoTransfer = new Transfer(smoDatabase);
                            smoTransfer.Options.DriAll = true;
                            smoTransfer.Options.SchemaQualify = true;
                            smoTransfer.Options.TargetServerVersion = SqlServerVersion.Version90;
                            smoTransfer.Options.WithDependencies = true;
                            smoTransfer.Options.IncludeDatabaseContext = true;
                            smoTransfer.CopyAllObjects = true;
                            foreach (string s in smoTransfer.ScriptTransfer())
                            {
                                scriptResult.Append(s);
                                scriptResult.Append(Environment.NewLine);
                            }

                        }

                        string fileName = string.Empty;
                        for (int i = 0; i < databaseName.Length; i++)
                        {
                            if (char.IsLetterOrDigit(databaseName[i]))
                            {
                                fileName += databaseName[i];
                            }
                        }

                        Response.Clear();
                        Response.AddHeader("Content-Type:", "text/plain");
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + "_export.sql");
                        Response.Write(scriptResult.ToString());
                        Response.End();

                    }


                }
                catch (SmoException smoEx)
                {
                    lblError.Text = HttpUtility.HtmlEncode(Common.ConcatenateExceptions(smoEx));
                    lblError.Visible = true;
                }
                catch (System.Threading.ThreadAbortException)
                {
                    // Do nothing.
                }
                catch (System.Exception ex)
                {
                    lblError.Text = HttpUtility.HtmlEncode(Common.ConcatenateExceptions(ex));
                    lblError.Visible = true;
                }
                
            
        }
    }
}
